<template>
  <div>
    <div class="tw-multi-transfer">
      <input type="text" readonly :placeholder="placeholder" v-model="inputvalue" @click="onCooper">
    </div>
    <CooperModify :modifyId="cooperId" :visible="cooperModify" @on-close-codify="onCooperClose" @submit="onSubmit" :formConfig="formConfig" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { FORM_CHANGE_EVENT_KEY } from '@/materials/setters/constant'
import CooperModify from '@/materials/components/CooperMember/CooperModify.vue'
import { termPurviewSave as saveCollaborator } from '@/management/api/dataform-extend'
import { CODE_MAP } from '@/management/api/eco/base'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'

interface Props {
  readonly?: boolean,
  formId: string,
  formConfig: any
}

interface Emit {
  (ev: typeof FORM_CHANGE_EVENT_KEY, arg: { key: string; value: Array<string> }): void
}

const emit = defineEmits<Emit>()
const props = withDefaults(defineProps<Props>(), {
  readonly: false
})

const modelValue = ref<any[]>([])
const inputvalue = ref('')
const placeholder = computed(() => props.formConfig.placeholder || props.formConfig.label)

const handleSelectChange = (value: Array<string>) => {
  const key = props.formConfig.key

  emit(FORM_CHANGE_EVENT_KEY, { key, value })
}

const cooperModify = ref(false)
const cooperId = ref('')
const onCooper = async () => {
  if (props.readonly) {
    return
  }
  cooperId.value = props.formId || 'row._id'
  cooperModify.value = true
}
const onCooperClose = () => {
  cooperModify.value = false
}
const onSubmit = async (val: any) => {
  let purviewList: any[] = []
  val.forEach((v: any) => {
    purviewList.push({
      objectId: v.value,
      useLimit: '2'
    })
  })
  const res: any = await saveCollaborator({
    formId: props.formId,
    purviewList: purviewList
  })
  if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
    modelValue.value = val
    inputvalue.value = modelValue.value.map(v => v.label).join(',')
    handleSelectChange(val)
    onCooperClose()
    // ElMessage.success('操作成功')
  } else {
    ElMessage.error(res?.serverResult?.resultMessage || '共享管理接口保存失败')
  }
}

watch(
  () => props.formConfig?.value,
  (val) => {
    modelValue.value = val
    inputvalue.value = modelValue.value.map(v => v.label).join(',')
  },
  { immediate: true, deep: true }
)
</script>
<style lang="scss" scoped>
.tw-multi-transfer {
  display: flex;
  input {
    outline: none;
    background-color: #fff;
    vertical-align: top;
    border: 1px solid #dcdef6;
    width: 440px;
    text-overflow: ellipsis;
    height: 32px;
    transform-origin: left top;
    box-sizing: border-box;
    overflow: hidden;
    color: #6e707c;
    font-size: 14px;
    padding: 12px;
    border-radius: 4px;
  }
}

</style>
